package com.oig.sys.msg.thread;

import com.oig.sys.msg.app.IAppNoticeMsgService;
import com.oig.sys.msg.dto.NoticeMsgDto;
import com.oig.sys.msg.vo.NoticeMsgVo;
import com.oig.sys.security.util.SecurityUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


/**
 * 飞书、企微消息发送
 */
@Slf4j
public class MsgPublisher {

    private final IAppNoticeMsgService appNoticeMsgService;

    public MsgPublisher(IAppNoticeMsgService appNoticeMsgService) {
        this.appNoticeMsgService = appNoticeMsgService;
    }


    private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    public void start() {
        log.info("MsgPublisher Polling Thread start...");
        executor.scheduleWithFixedDelay(this::findAndSendMsg, 0, 1, TimeUnit.SECONDS);
    }

    private void findAndSendMsg() {
        //log.debug("站内消息轮询开始");
        try {
            List<NoticeMsgVo> noticeMsgVos = appNoticeMsgService.findUnSendMsg();
            log.debug("站内消息轮询查询结果：{}", noticeMsgVos == null ? null : noticeMsgVos.size());
            if (noticeMsgVos != null && !noticeMsgVos.isEmpty()) {
                noticeMsgVos.forEach(this::dealSendMsg);
            }
        } catch (Exception e){
            log.error("站内消息轮询出错", e);
        }
    }

    private void dealSendMsg(NoticeMsgVo noticeMsgVo) {
        try {
            if (noticeMsgVo.getPublisherTime() == null) {
                if (noticeMsgVo.getPubTime() != null && noticeMsgVo.getPubTime().before(new Date())) {
                    NoticeMsgDto noticeMsgDto = new NoticeMsgDto();
                    noticeMsgDto.setId(noticeMsgVo.getId());
                    noticeMsgDto.setPublisherId(SecurityUtil.getSys().getId());
                    noticeMsgDto.setPublisherName(SecurityUtil.getSys().getRealName());
                    noticeMsgDto.setPublisherTime(new Date());
                    log.debug("准备推送..");
                    noticeMsgVo = this.appNoticeMsgService.publishMsg(noticeMsgDto);
                }
            }
            //有发布时间的，就推送
            if (noticeMsgVo.getPublisherTime() == null) {
                log.debug("消息发布时间未到，不推送。。");
                return;
            }
            log.debug("发送消息。。");
            this.appNoticeMsgService.pushMsg(noticeMsgVo);
        } catch (Exception e){
            log.error("站内消息轮询出错",e);
        }
    }


    public void toStop() {
        executor.shutdown();
    }

}
